﻿#define _CRT_SECURE_NO_WARNINGS 1
#include "seqList.h"

//初始化和销毁
void SLInit(SL* ps)
{
	assert(ps);//防止传入空指针
	int Capacity = sizeof(SLDataType) * INIT_CAPACITY;
	//初始化
	ps->data = (SLDataType*)malloc(Capacity);
	if (ps->data == NULL)
	{
		perror("malloc");
		exit(-1);
	}

	memset(ps->data, 0, Capacity);//给动态开辟的空间初始化为0
	ps->capacity = INIT_CAPACITY;
	ps->size = 0;
}

void SLDestroy(SL* ps)
{
	assert(ps);
	free(ps->data);
	ps->data = NULL;
	ps->capacity = 0;
	ps->size = 0;
	ps = NULL;
}

void Print(const SL* ps)
{
	assert(ps);

	int i = 0;
	for (i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->data[i]);
	}
	printf("\n");
}

static void Expansion(SL* ps)
{
	//数据满了
	if (ps->capacity == ps->size)
	{
		//进行扩容
		int Capacity = ps->capacity * MULTIPLE;
		SLDataType* tmp = (SLDataType*)realloc(ps->data, sizeof(SLDataType) * Capacity);
		if (tmp == NULL)
		{
			perror("realloc");
			exit(-1);
		}
		ps->data = tmp;
		tmp = NULL;
		ps->capacity = Capacity;
	}
}

//尾插
void SLPushBack(SL* ps, SLDataType data)
{
	assert(ps);
	Expansion(ps);//检查容量,不够就扩容

	ps->data[ps->size] = data;
	ps->size++;
}

//尾删
void SLPopBack(SL* ps)
{
	assert(ps);
	assert(ps->size > 0);

	ps->size--;
}

//头插
void SLPushFront(SL* ps, SLDataType data)
{
	assert(ps);
	Expansion(ps);//检查容量,不够就扩容
	int i = 0;
	for (i = ps->size; i >= 0; i--)
	{
		ps->data[i] = ps->data[i - 1];
	}

	ps->data[0] = data;
	ps->size++;
}

//头删
void SLPopFront(SL* ps)
{
	assert(ps);
	assert(ps->size > 0);
	int i = 0;
	for (i = 0; i < ps->size-1; i++)
	{
		ps->data[i] = ps->data[i + 1];
	}

	ps->size--;
}

int SLFind(const SL* ps, SLDataType data)
{
	assert(ps);
	int i = 0;
	for (i = 0; i < ps->size; i++)
	{
		if (ps->data[i] == data)
			return i;//找到了，返回下标
	}

	return -1;//没找到
}

//指定位置之前插⼊数据
void SLInsert(SL* ps,int pos, SLDataType data)
{
	assert(ps);//防止传入NULL指针
	assert(pos >= 0 && pos < ps->size);//检查pos是否是一个正确的位置

	Expansion(ps);//检查容量,不够就扩容

	int i = 0;
	for (i = ps->size; i > pos; i--)
	{
		ps->data[i] = ps->data[i - 1];
	}

	ps->data[pos] = data;
	ps->size++;
}

// 删除指定位置之前数据
void SLErase(SL* ps, int pos)
{
	assert(ps);//防止传入NULL指针
	assert(pos > 0 && pos < ps->size);//检查pos是否在范围内

	int i = 0;
	//pos = 1
	// 1 2 3 4
	for (i = pos; i < ps->size; i++)
	{
		ps->data[i - 1] = ps->data[i];
	}

	ps->size--;
}